<template>
    <div class="content">
        <Form :label-width="200" :model="form" :rules="rules" ref="form" v-show="step === 1">
            <FormItem label="所属分类" prop="sortId">
                <Select v-model="form.sortId" style="width: 200px;margin-right:10px;" clearable>
                    <Option v-for="item in sList" :key="item.id" :value="item.id">{{item.name}}</Option>
                </Select>
                <Button @click="handleAddSort">增加分类</Button>
            </FormItem>
            <FormItem label="试题导入" prop="fileName">
                <div>
                    <div class="answer-file">
                        <div class="file-name">{{ form.fileName }}</div>
                        <div>请按模版要求填写：<a @click="download">下载模版</a></div>
                    </div>
                    <Upload
                        class="answer-upload-btn"
                        :beforeUpload="beforeUpload"
                        :action="action"
                        :headers="headers"
                        :accept="accept"
                        :format="format"
                        :maxSize="20480"
                        :on-format-error="onFormatError"
                        :on-exceeded-size="onExceededSize"
                        :on-success="res => onUploadSuccess(res)"
                        :show-upload-list="false"
                    >
                        <Button>选择文件</Button>
                    </Upload>
                </div>
                <div>提示：单次导入不可超过500题</div>
            </FormItem>
            <FormItem>
                <div class="submit-footer">
                    <Button type="primary" @click="nextStep" v-if="step === 1">下一步</Button>
                    <Button @click="handleCancel">取消</Button>
                </div>
            </FormItem>
        </Form>
        <div v-show="step === 2">
            <div>成功导入{{cgts}}题，失败{{sbts}}题</div>

            <div class="export-result">
                <div class="question-item" v-for="(item,index) in testList" :key="index">
                    <div class="question-content" v-if="!item.del" >
                        <div class="question-side question-form">
                            <div class="form-item">
                                <div class="form-label">所属分类</div>
                                <div class="form-content">
                                    <Select size="small" v-model="item.sortId" style="width: 100px;" clearable>
                                        <Option v-for="one in sList" :key="one.id" :value="one.id">{{one.name}}</Option>
                                    </Select>
                                </div>
                            </div>

                            <div class="form-item">
                                <div class="form-label">题型{{item.type}}</div>
                                <div class="form-content">
                                    <Select v-model="item.type" placeholder="题型" style="width:100px" clearable>
                                        <Option v-for="(one) in questionTypeArr" :key="one.id" :value="one.id">{{ one.name }}</Option>
                                    </Select>
                                </div>
                            </div>
                            <div class="form-item">
                                <div class="form-label">分值</div>
                                <div class="form-content">
                                    <Input size="small" v-model="item.score" style="width: 80px;margin-right:10px;" type="number"></Input>
                                    <span>分</span>
                                </div>
                            </div>
                            <div class="form-item">
                                <div class="form-label">难度</div>
                                <div class="form-content">
                                    <Select v-model="item.difficulty" placeholder="难度" style="width:100px" clearable>
                                        <Option v-for="(one) in questionDifficultyArr" :key="one.id" :value="one.id">{{ one.name }}</Option>
                                    </Select>
                                </div>
                            </div>
                        </div>
                        <div class="question-info">
                            <div> <span class="nexth">{{item.topic}} （ ）</span></div>
                            <div v-if="item.type==1||item.type==2">
                                <div v-for="(item,index) in (item.opt).split('|')" :key="index">
                                    <span v-if="index==0">A:{{item}}</span>
                                    <span v-if="index==1">B:{{item}}</span>
                                    <span v-if="index==2">C:{{item}}</span>
                                    <span v-if="index==3">D:{{item}}</span>
                                    <span v-if="index==4">E:{{item}}</span>
                                </div>
                            </div>
                            <div>答案:<span class="nexth">{{item.answer}}</span></div>
                            <div>解析:<span class="nexth">{{item.analysis}}</span></div>
                        </div>
                    </div>
                    <div class="btns" v-if="!item.del">
                        <Button @click="setDelete(item)" type="warning">删除</Button>
                    </div>
                </div>
            </div>
            <div class="submit">
                <Button type="primary" @click="submit" v-if="step === 2">保存</Button>
                <Button @click="handleCancel">取消</Button>
            </div>
        </div>
    </div>
</template>
<script>
import config from '@/config'
import { getToken } from '@/libs/util'
import { questionTypeArr, questionDifficultyArr } from '@/libs/enums'
import { sortList, importQuestion, saveQuestion } from '@/api/questionManage'
import { downloadTemplate } from '@/api/fileManage'
export default {
    data () {
        return {
            cgts: 0,
            sbts: 0,
            questionTypeArr,
            questionDifficultyArr,
            testList: [],
            sList: [],
            step: 1,
            accept: '.xls,.xlsx',
            format: Object.freeze(['xls', 'xlsx']),
            headers: Object.freeze({
                Authorization: getToken()
            }),
            action: config.uploadUrl,
            importString: '',
            form: {
                sortId: '',
                file: '',
                fileName: ''
            },
            rules: {
                sortId: [
                    {
                        required: true,
                        message: '所属分类必选',
                        trigger: 'change'
                    }
                ],
                fileName: [{ required: true, message: '请导入试题', trigger: 'change' }]
            }
        }
    },
    inject: ['nextPageReload'],
    mounted () {
        this.getType()
    },
    methods: {
        setDelete (one) {
            console.log(one)
            one.del = true
        },
        download (type) {
            downloadTemplate({
                fileFlag: 2
            })
        },
        // 导入前拦截
        beforeUpload (file) {
            console.log(file)
            if (this.checkFileFormat(file) && this.checkFileSize(file)) {
                this.form.file = file
                this.form.fileName = file.name
            } else {
                this.file = ''
                this.form.fileName = ''
            }
            return false
        },
        // 检查文件格式
        checkFileFormat (file) {
            const fileNameList = file.name.split('.')
            const fileFormat = fileNameList[fileNameList.length - 1].toLocaleLowerCase()
            if (this.format.indexOf(fileFormat) < 0) {
                this.$Message.warning(`不支持格式`)
                return false
            }
            return true
        },
        // 检查文件大小
        checkFileSize (file) {
            const maxSize = this.size * 1024 * 1024
            if (file.size > maxSize) {
                this.$Message.warning(`文件${file.name}不能超过${this.size}M`)
                return false
            }
            return true
        },
        getType () {
            let params = {
                pageNum: 1,
                pageSize: 999,
                schoolId: '',
                sequence: '',
                sort: '',
                sortId: ''
            }
            sortList(params).then(res => {
                console.log(res)
                this.sList = res.data.data.list.map(item => {
                    return {
                        id: item.sortId,
                        name: item.sort
                    }
                })
            })
        },
        handleAddSort () {
            this.$router.push({ name: 'testQuestionsSort' })
        },
        nextStep () {
            console.log(this.form.file)
            this.$refs.form.validate(v => {
                if (v) {
                    let a = { sortId: this.form.sortId, type: 'importTestServiceImpl' }
                    let b = JSON.stringify(a)
                    let c = { params: b }
                    let data = new FormData()
                    data.append('file', this.form.file)
                    importQuestion(c, data).then(res => {
                        console.log(res)
                        if (res.data.code === '0000') {
                            let errList = res.data.data.errorList
                            if (errList.length > 0) {
                                let mes = errList.join(',')
                                this.$Message.warning(`${mes}`)
                            } else {
                                this.testList = res.data.data.testList.map(v => {
                                    return { ...v, del: false }
                                })
                                this.cgts = res.data.data.successNum
                                this.sbts = res.data.data.failedNum
                                this.step++
                            }
                        } else {
                            console.log(res.data)
                            if (res.data.data) {
                                this.$Message.error(res.data)
                            } else {
                                this.$Message.error('导入失败')
                            }
                        }
                    })
                }
            })
            // this.step++;
        },
        submit () {
            saveQuestion(this.testList).then(res => {
                if (res.data.code != '0000') {
                    this.message.error(res.data.msg)
                    return
                }
                this.$Message.success('保存成功')
                this.nextPageReload()
                this.$router.push({
                    name: 'testQuestionsList',
                    query: {

                    }
                })
            })
        },
        handleCancel () {
            this.nextPageReload()
            this.$router.push({
                name: 'testQuestionsList',
                query: {

                }
            })
        },
        onFormatError () {
            this.$Message.error('文件格式有误')
        },
        onExceededSize () {
            this.$Message.error('文件大小超出可上传范围')
        },
        onUploadSuccess (res) {
            if (res.code === '0000') {
                const data = res.data || +new Date()
                if (data) {
                    this.form.file = data
                }
            } else {
                this.$Message.error(res.msg)
            }
        }
    }
}
</script>
<style lang="less" scoped>
.submit {
  text-align: center;
  margin-top: 15px;
  .ivu-btn + .ivu-btn {
    margin-left: 15px;
  }
}
.ivu-form {
  max-width: 800px;
}
.answer-upload-btn {
  display: inline-block;
  vertical-align: top;
}
.answer-file {
  &:extend(.answer-upload-btn);
  margin-right: 10px;
  .file-name {
    width: 300px;
    height: 33px;
    border: 1px solid #ccc;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: normal;
    padding: 0 10px;
  }
}
.export-result {
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 15px;
  .question-item {
    position: relative;
    & + .question-item {
      margin-top: 15px;
    }
  }
  .question-content {
    border: 1px solid #ccc;
    margin-right: 75px;
    padding: 10px 20px;
  }
  .btns {
    position: absolute;
    right: 0;
    top: 50%;
    transform: translateY(-50%);
  }
  .question-info {
    border-right: 1px solid #ccc;
    margin-right: 230px;
    min-height: 150px;
    padding-right: 15px;
  }
  .question-side {
    float: right;
    width: 220px;
  }
  .question-form {
    .form-item + .form-item {
      margin-top: 10px;
      line-height: 26px;
    }
    .form-label {
      width: 60px;
      float: left;
      text-align: right;
      line-height: 26px;
    }
    .form-content {
      margin-left: 70px;
    }
  }
}
.nexth{
    white-space:pre;
    white-space: normal;
}
</style>
